package com.yiyuzi.admin.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yiyuzi.admin.common.constant.ResponseCodeEnum;
import com.yiyuzi.admin.privilege.domain.entity.PrivilegeEntity;
import com.yiyuzi.admin.privilege.service.PrivilegeService;
import com.yiyuzi.admin.role.domain.entity.RolePrivilegeEntity;
import com.yiyuzi.admin.role.service.RolePrivilegeService;
import com.yiyuzi.admin.token.service.TokenService;
import com.yiyuzi.admin.user.domain.entity.UserRoleEntity;
import com.yiyuzi.admin.user.service.UserRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 拦截器
 *
 * @author yiyuzi
 * @date 2021/5/8 17:05
 */

@Component
public class AdminInterceptorAdapter implements HandlerInterceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(AdminInterceptorAdapter.class);
    @Resource
    private TokenService tokenService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RolePrivilegeService rolePrivilegeService;

    @Resource
    private PrivilegeService privilegeService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.info("================================== preHandle1 ===========================================");

        // 登录拦截
        StringBuffer url = request.getRequestURL();
        for(int i = 0; i < 3; i++)
            url.delete(0, url.indexOf("/")+1);
        LOGGER.info("{}", url);
        // 放行的url
        Pattern pattern = Pattern.compile("((.*.html)|(.*.js)|(.*.css)|(.*.ico)|(.*login))");
        if (pattern.matcher(url.toString()).find()){
            return true;
        }
        String token = request.getHeader("token");
        if (!tokenService.isValid(token)){
            LOGGER.info("无效token");
            response.setStatus(ResponseCodeEnum.TOKEN_INVALID.getValue());
//            response.getWriter();
            return false;
        }

        // 权限拦截，可以做个缓存，不用每次去数据库查
        Long user_id = tokenService.getUserByToken(token).getId();
        if (user_id == 1){
            // 放行超管
            return true;
        }
        List<UserRoleEntity> list1 = userRoleService.list(new QueryWrapper<UserRoleEntity>()
                .eq("user_id", user_id));
        for (UserRoleEntity entity1 : list1){
            List<RolePrivilegeEntity> list2 = rolePrivilegeService.list(new QueryWrapper<RolePrivilegeEntity>()
                    .eq(entity1.getRoleId() != null, "role_id", entity1.getRoleId()));
            for(RolePrivilegeEntity entity2 : list2){
                PrivilegeEntity privilegeEntity = privilegeService.getById(entity2.getPrivilegeId());
                if (privilegeEntity.getPath().equals(url.toString())){
                    return true;
                }
            }
        }
        LOGGER.error("无权限");
        response.setStatus(ResponseCodeEnum.NO_PRIVILEGE.getValue());
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LOGGER.info("================================== postHandle1 ===========================================");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LOGGER.info("================================== afterCompletion1 ===========================================");
    }
}
